#include "GameBoardView.h"
#include "GameBoard.h"
#include "GameBoardRendererThread.h"
#include <QDebug>
#include <QTimer>
#include <QMouseEvent>

GameBoardView::GameBoardView(GameBoard *board, bool playable, QWidget *parent)
  : QGLWidget(parent),
    mMouseOverTile(-1,-1),
    mPlayable(playable),
    mSelected(false),
    mBoard(board)
{
  setMouseTracking(mPlayable);
}

GameBoardView::~GameBoardView() {}

void GameBoardView::startRendering(unsigned int frameRate)
{
  mRendererThread = new GameBoardRendererThread(mBoard, this, 60);
  mRendererThread->resize(size());
  mRendererThread->start();
}

void GameBoardView::setPlayable(bool playable)
{
  mPlayable = playable;
  setMouseTracking(mPlayable);
}

void GameBoardView::setSelected(bool selected)
{
  mSelected = selected;
}

bool GameBoardView::selected() const
{
  return mSelected;
}

void GameBoardView::mousePressEvent(QMouseEvent *e)
{
  if (mPlayable)
  {
    int tw = mWidth/mBoard->rows(),
        th = mHeight/mBoard->cols();
    QPoint p(e->x()/tw,(mHeight-e->y())/th);
    mBoard->clickAt(p);
  }
  else
  {
    mSelected = !mSelected;
  }
}

void GameBoardView::mouseMoveEvent(QMouseEvent *e)
{
  if (mPlayable)
  {
    int tw = mWidth/mBoard->rows(),
        th = mHeight/mBoard->cols();
    if (mMouseOverTile.x() != e->x()/tw ||
        mMouseOverTile.y() != (mHeight-e->y())/th)
    {
      mMouseOverTile.setX(e->x()/tw);
      mMouseOverTile.setY((mHeight-e->y())/th);
      mRendererThread->setMousePosition(mMouseOverTile);
    }
  }
}

void GameBoardView::resizeEvent(QResizeEvent *e)
{
  mWidth = e->size().width();
  mHeight = e->size().height();
  mRendererThread->resize(e->size());
}

void GameBoardView::closeEvent(QCloseEvent *e)
{
  mRendererThread->stop();
  mRendererThread->wait();
  QGLWidget::closeEvent(e);
}
